package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author whr
 * @version 1.0
 * @description: 课程信息管理业务接口实现类
 * @date 2024/2/29 14:08
 */
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    /**
     * @Description: 课程信息分页查询
     * @Author: whr
     * @Date: 2024/3/2 14:36
     * @Param:
     * @Return:
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //构建条件查询对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());
        //构建查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        //构建查询条件，根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());

        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<CourseBase> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;


    }

    /**
     * @Description: 新增课程基本信息
     * @Author: whr
     * @Date: 2024/3/1 20:00
     * @Param:
     * @Return:
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
        //合法性校验
        if (StringUtils.isBlank(dto.getName())) {
            XueChengPlusException.cast("课程名称为空");
        }
        if (StringUtils.isBlank(dto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        }
        //创建对象
        CourseBase courseBase = new CourseBase();
        //从dto拷贝数据
        BeanUtils.copyProperties(dto, courseBase);
        //设置机构id
        courseBase.setCompanyId(companyId);
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
        //设置添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        int insert = courseBaseMapper.insert(courseBase);
        Long courseId = courseBase.getId();

        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto, courseMarket);
        courseMarket.setId(courseId);
        //将
        int insert1 = saveCourseMarket(courseMarket);
        if (insert <= 0 || insert1 <= 0) {
            throw new RuntimeException("新增课程基本信息失败");
        }
        return getCourseBaseInfoDto(courseId);
    }

    /**
     * @Description: 封装要返回给前端的数据CourseBaseInfoDto
     * @Author: whr
     * @Date: 2024/3/1 21:46
     * @Param:
     * @Return:
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfoDto(Long courseId) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        CourseCategory mtName = courseCategoryMapper.selectById(courseBase.getMt());
        CourseCategory stName = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setMtName(mtName.getName());
        courseBaseInfoDto.setStName(stName.getName());
        return courseBaseInfoDto;
    }

    /**
     * @Description: 更新课程信息
     * @Author: whr
     * @Date: 2024/3/1 21:49
     * @Param:
     * @Return:
     */
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) {
        //获取课程id
        Long id = dto.getId();
        //防止多线程情况，即有别的用户删除了该课程，但有别的用户仍在编辑该课程，停留
        //在修改课程界面，需要重新查询是否还有该课程
        CourseBase courseBase = courseBaseMapper.selectById(id);
        //如果无该课程，抛出异常
        if (courseBase == null) {
            XueChengPlusException.cast("该课程不存在");
        }
        //确认修改权限
        if (!companyId.equals(courseBase.getCompanyId())) {
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }
        //封装数据
        BeanUtils.copyProperties(dto, courseBase);
        //更新修改时间
        courseBase.setChangeDate(LocalDateTime.now());
        //更新数据库
        int i = courseBaseMapper.updateById(courseBase);
        if (i <= 0) {
            XueChengPlusException.cast("修改课程失败");
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        //如果该课程的营销信息为空，则创建数据并更新数据库
        //不为空直接拷贝属性进行更新
        if (courseMarket == null) {
            courseMarket = new CourseMarket();
            BeanUtils.copyProperties(dto, courseMarket);
            courseMarket.setId(id);
            courseMarketMapper.insert(courseMarket);
        } else {
            BeanUtils.copyProperties(dto, courseMarket);
            courseMarketMapper.updateById(courseMarket);
        }
        return getCourseBaseInfoDto(id);
    }

    /**
     * @Description: 课程营销信息入库
     * @Author: whr
     * @Date: 2024/3/2 14:34
     * @Param:
     * @Return:
     */
    private int saveCourseMarket(CourseMarket courseMarketNew) {
        //参数合法性校验
        String charge = courseMarketNew.getCharge();
        if (org.springframework.util.StringUtils.isEmpty(charge)) {
            throw new RuntimeException("收费规则为空");
        }
        //收费规则为收费要校验价格是否为空并且是否合理
        if (charge.equals("201001")) {
            if (courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue() <= 0) {
                throw new RuntimeException("价格不能为空且必须大于0");
            }
        }
        //无则插入，有则更新
        Long id = courseMarketNew.getId();
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if (courseMarket == null) {
            return courseMarketMapper.insert(courseMarketNew);
        } else {
            return courseMarketMapper.updateById(courseMarketNew);
        }
    }

}
